package com.imay.live.activity.video;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.imay.live.Constants;
import com.imay.live.activity.dynamics.ReleaseActivity;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.fragment.room.BeautyFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.HWSupportList;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.view.AutoAdjustItemClickListener;
import com.imay.live.view.AutoAdjustRecylerView;
import com.imay.live.R;
import com.tencent.rtmp.ugc.TXRecordCommon;
import com.tencent.rtmp.ugc.TXUGCRecord;
import com.tencent.rtmp.ui.TXCloudVideoView;

/**
 * Created by chan on 2017/6/5 0005.
 */

public class RecordVideoActivity extends FragmentActivity implements TXRecordCommon.ITXVideoRecordListener, View.OnClickListener, BeautyFragment.OnBeautyChangeListener, View.OnLongClickListener {

    private Context mContext;

    private boolean mRecording = false;
    private TXUGCRecord mTXCameraRecord = null;
    private TXCloudVideoView mVideoView;
    private TextView mTvRecordTime;
    private ImageView mBtnOk, mBtnSwitch;
    private VideoProgressView mProgressView;
    private AutoAdjustRecylerView mRecyclerView;
    private RelativeLayout mBottom;
    private ImageView mIvflash;
    private ImageView mBtnRecord;
    private ImageView mPause;

    private boolean mHWDecode = false;
    private final int videoQuality = TXRecordCommon.VIDEO_QUALITY_MEDIUM;
    private boolean mFront = true;
    private long mStartRecordTimeStamp;
    private TXRecordCommon.TXRecordResult mTxRecordResult;
    private int mIvflashMode = 0; //0、禁止闪关灯；1、关闭；2、开启

    private GestureDetector mGestureDetetor;
    private RecordVideoActivity.State state;
    private boolean isFinishing = false;


    private enum State {NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM}

    private BeautyFragment mBeautyFragment;
    private boolean muxering;


    AudioManager mAudioManager;
    AudioManager.OnAudioFocusChangeListener mOnAudioFocusListener;


    public static void startActivity(FragmentActivity activity) {
        Intent intent = new Intent(activity, RecordVideoActivity.class);
        activity.startActivity(intent);
    }

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, RecordVideoActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FilterHelper.getInstance().initFilter(this);

        setContentView(getLayoutId());

        mGestureDetetor = new GestureDetector(this, new RecordVideoActivity.GestureDetetor());

        initDatas();

        initView(savedInstanceState);

        initListener();
        MobclickAgent.onEvent(this, "video_open");
    }

    protected int getLayoutId() {
        return R.layout.activity_videorecord;
    }

    private void initDatas() {
        mContext = this;

        mHWDecode = HWSupportList.isHWVideoEncodeSupport();
    }

    protected void initView(Bundle savedInstanceState) {
        int beautyLevel = PreferenceHelper.getInstance().getBeautyLevel(8);
        int whiteningLevel = PreferenceHelper.getInstance().getWhiteningLevel(7);
        int ruddyLevel = PreferenceHelper.getInstance().getRuddyLevel(7);

        initPlayer(beautyLevel, whiteningLevel, ruddyLevel);

        // 确认按钮init及listener
        mBtnOk = $(R.id.btn_ok);
        // 切换摄像头
        mBtnSwitch = $(R.id.iv_switch_camera);

        // 录制时间
        mTvRecordTime = $(R.id.tv_record_time);
        mTvRecordTime.setText(getString(R.string.str_record_video));

        mBeautyFragment = BeautyFragment.newInstance(beautyLevel, whiteningLevel, ruddyLevel);

        mBottom = $(R.id.rl_bottom);

        mIvflash = $(R.id.iv_flash);

        changeFlash();

        mBtnRecord = $(R.id.btn_record);

        mRecyclerView = $(R.id.recyclerView);
        FilterHelper.getInstance().initFilterDatas(mRecyclerView);

        mPause = $(R.id.iv_camera_pause);
    }

    private void initListener() {
        mBtnOk.setOnClickListener(this);
        mBtnSwitch.setOnClickListener(this);
        mIvflash.setOnClickListener(this);
        mBtnRecord.setOnClickListener(this);
        mBtnRecord.setOnLongClickListener(this);

        //注册广播
        registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

        mBtnRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (view.getId() == R.id.btn_record) {
                    final int width = mBtnRecord.getMeasuredWidth();
                    final int height = mBtnRecord.getMeasuredHeight();
                    double y = motionEvent.getY();
                    double x = motionEvent.getX();
                    if (x < 0 || x > width || y < 0 || y > height) {
                        if (mRecording) {
                            stopRecord();
                            return true; // 不给child或者其他事件获取
                        }
                    }
                }
                return false;
            }
        });

        // 滤镜选择
        mRecyclerView.setItemClickListener(new AutoAdjustItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                if (!mRecording) {
                    FilterHelper.Filter filter = FilterHelper.getInstance().getBitmap(postion);
                    Bitmap bmp = null;
                    if (filter.rid != -1) {
                        bmp = BitmapFactory.decodeResource(getResources(), filter.rid);
                    }
                    if (mTXCameraRecord != null) {
                        mTXCameraRecord.setFilter(bmp);
                        FilterAdapter mAdapter = (FilterAdapter) mRecyclerView.getAdapter();
                        mAdapter.setSelectedPostion(postion);
                        mRecyclerView.checkAutoAdjust(postion);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

        mVideoView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getPointerCount() == 1) {
                    mGestureDetetor.onTouchEvent(event);
                }
                return true;
            }
        });
    }

    /**
     * 初始化player
     *
     * @param beautyLevel
     * @param whiteningLevel
     */
    private void initPlayer(int beautyLevel, int whiteningLevel, int ruddyLevel) {
        mVideoView = $(R.id.glsurfaceview_camera);
        mVideoView.enableHardwareDecode(mHWDecode);
        mTXCameraRecord = TXUGCRecord.getInstance(this.getApplicationContext());
        // 预览
        if (mTXCameraRecord == null) {
            mTXCameraRecord = TXUGCRecord.getInstance(RecordVideoActivity.this.getApplicationContext());
        }
        TXRecordCommon.TXUGCSimpleConfig param = new TXRecordCommon.TXUGCSimpleConfig();
        param.videoQuality = videoQuality;
        param.isFront = mFront;     //是否前置摄像头，使用 switchCamera 可以切换
        int result = mTXCameraRecord.startCameraSimplePreview(param, mVideoView);
//        mTXCameraRecord.setBeautyDepth(0, beautyLevel, whiteningLevel, ruddyLevel);
        mTXCameraRecord.setBeautyDepth(beautyLevel, whiteningLevel);
    }

    private void changeFlash() {
        if (mFront) {
            mIvflash.setImageResource(R.mipmap.btn_03_camera_flash_clos_disable);
            mIvflashMode = 0;
        } else {
            mIvflash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
            mIvflashMode = 1;
        }
    }

    @Override
    public void onRecordEvent(int i, Bundle bundle) {
    }

    private boolean isProgress = false;

    @Override
    public void onRecordProgress(long milliSecond) {
        if (!isProgress) {
            ImageView mBtnRecord = $(R.id.btn_record);
            if (mBtnRecord != null) {
                mBtnRecord.setSelected(false);
            }
            mPause.setVisibility(View.VISIBLE);
            mProgressView.setCurrentState(VideoProgressView.State.DELETE);
            mProgressView.clearTimeList();
            mProgressView.setCurrentState(VideoProgressView.State.START);
            isProgress = true;
        }
        if (mProgressView != null) {
            float l = milliSecond / 100;
            int time = (int) (600 - l);
            mTvRecordTime.setText(String.format("%.1f", time / 10f));
            if (milliSecond >= 60000.0f) {
                stopRecord();
                isFinishing = true;
                mTvRecordTime.setText("0.0");
            } else if (milliSecond >= 3000.0f) {
                mBtnOk.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onRecordComplete(TXRecordCommon.TXRecordResult txRecordResult) {
        muxering = false;
        mTxRecordResult = txRecordResult;
    }

    @Override
    public boolean onLongClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_record) {
            if (!mRecording) {
                startRecord();
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_record:
                switchRecord();
                MobclickAgent.onEvent(RecordVideoActivity.this, "video_click_taken");
                break;
            case R.id.iv_flash:
                if (mRecording) {
                    return;
                }
                if (mIvflashMode == 1) {
                    mIvflash.setImageResource(R.mipmap.btn_03_camera_flash_default);
                    mIvflashMode = 2;
                    if (mTXCameraRecord != null) {
                        mTXCameraRecord.toggleTorch(true);
                    }
                } else if (mIvflashMode == 2) {
                    mIvflash.setImageResource(R.mipmap.btn_03_camera_flash_clos);
                    mIvflashMode = 1;
                    if (mTXCameraRecord != null) {
                        mTXCameraRecord.toggleTorch(false);
                    }
                }
                break;
            case R.id.btn_ok:
                if (mRecording) { // 正在录制时需暂停
                    stopRecord();
                }
                clickOk();
                MobclickAgent.onEvent(RecordVideoActivity.this, "video_click_upload");
                break;
            case R.id.iv_switch_camera:
                if (mRecording) {
                    return;
                }
                mFront = !mFront;
                if (mTXCameraRecord != null) {
                    mTXCameraRecord.switchCamera(mFront);
                }
                changeFlash();
                break;
            case R.id.iv_close:
                if (mRecording && mTXCameraRecord != null) {
                    mTXCameraRecord.stopRecord();
                    mTXCameraRecord.setVideoRecordListener(null);
                }
                finish();
                break;
            case R.id.iv_beauty:
                if (mRecording) {
                    return;
                }
                DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), mBeautyFragment);
                if (mBottom != null) {
                    mBottom.setVisibility(View.INVISIBLE);
                }
                break;
        }
    }

    private void clickOk() {
        /**
         * 当LoadingDialog为100时才结束控制
         */
        int time = 400;
        //mBtnRecord.setSelected(false);
        mPause.setVisibility(View.GONE);
        LoadingDialogFragment.show(this, getFragmentManager(), time, new LoadingDialogFragment.OnLoadingListener() {
            @Override
            public void onShow() {
                new Thread(muercheck).start();
            }

            @Override
            public void onDimiss() {
                if (TextUtils.isEmpty(mTxRecordResult.coverPath)) {
                    DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getString(R.string.str_release_file), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    });
                    return;
                }
                ReleaseActivity.startActivity(RecordVideoActivity.this, mTxRecordResult.coverPath, mTxRecordResult.videoPath, null, ReleaseActivity.MOVIE, Constants.DYNAMICSFEED_REQUEST_CODE);
            }
        });
    }

    private void switchRecord() {
        if (mRecording) {
            stopRecord();
        } else {
            if (!isFinishing) {
                //mBtnRecord.setSelected(true);
                startRecord();
            } else {
                isFinishing = false;
            }
        }
    }

    /**
     * 开始录像
     */
    private void startRecord() {
        abandonAudioFocus();
        mRecyclerView.setIsRecording(true);
        mTxRecordResult = null;
        muxering = true;
        if (mTXCameraRecord == null) {
            mTXCameraRecord = TXUGCRecord.getInstance(this.getApplicationContext());
        }
        mProgressView = $(R.id.recorder_progress);
        mTXCameraRecord.setVideoRecordListener(this);
        int result = mTXCameraRecord.startRecord();
        if (result != 0) {
            Toast.makeText(mContext, "录制失败，错误码：" + result, Toast.LENGTH_SHORT).show();
            mTXCameraRecord.setVideoRecordListener(null);
            mTXCameraRecord.stopRecord();
            return;
        }
        mRecording = true;
        mStartRecordTimeStamp = System.currentTimeMillis();

        mBtnOk.setVisibility(View.INVISIBLE);
        isProgress = false;
        requestAudioFocus();
    }

    // 监听空事件
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";
        String SYSTEM_HOME_KEY_LONG = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    //表示按了home键,程序到了后台
                    //Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
                    if (mRecording) {
                        //mBtnRecord.setSelected(false);
                        mPause.setVisibility(View.GONE);
                        stopRecord();
                    }
                }
            }
        }
    };

    /**
     * 停止录像
     */
    private void stopRecord() {
        //mBtnRecord.setSelected(false);
        mPause.setVisibility(View.GONE);
        mRecyclerView.setIsRecording(false);
        abandonAudioFocus();
        ImageView mBtnRecord = $(R.id.btn_record);
        if (mBtnRecord != null) {
            mBtnRecord.setSelected(false);
        }
        mRecording = false;
        mProgressView.setCurrentState(VideoProgressView.State.PAUSE);
        mProgressView.putTimeList((int) ((System.currentTimeMillis() - mStartRecordTimeStamp)));
        // 录制时间要大于3s
        if (System.currentTimeMillis() < mStartRecordTimeStamp + 3 * 1000) {
            mTvRecordTime.setText(getString(R.string.str_record_video));
            mProgressView.setCurrentState(VideoProgressView.State.DELETE);
            mProgressView.clearTimeList();
            if (mTXCameraRecord != null) {
                mTXCameraRecord.setVideoRecordListener(null);
                mTXCameraRecord.stopRecord();
            }
        } else {
            if (mTXCameraRecord != null) {
                mTXCameraRecord.stopRecord();
            }
        }
    }

    /**
     *
     */
    private void requestAudioFocus() {
        if (null == mAudioManager) {
            mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        }

        if (null == mOnAudioFocusListener) {
            mOnAudioFocusListener = new AudioManager.OnAudioFocusChangeListener() {

                @Override
                public void onAudioFocusChange(int focusChange) {
                    try {
                        if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                            mTXCameraRecord.setVideoRecordListener(null);
                            stopRecord();
                        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                            mTXCameraRecord.setVideoRecordListener(null);
                            stopRecord();
                        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            };
        }
        try {
            mAudioManager.requestAudioFocus(mOnAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void abandonAudioFocus() {
        try {
            if (null != mAudioManager && null != mOnAudioFocusListener) {
                mAudioManager.abandonAudioFocus(mOnAudioFocusListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 简化
     *
     * @param id
     * @param <T>
     * @return
     */
    private <T extends View> T $(int id) {
        return (T) findViewById(id);
    }

    @Override
    public void onBeautyChange(int beautyLevel, int whiteningLevel, int ruddyLevel) {
        PreferenceHelper.getInstance().saveBeautyLevel(beautyLevel);
        PreferenceHelper.getInstance().saveWhiteningLevel(whiteningLevel);
//        mTXCameraRecord.setBeautyDepth(0, beautyLevel, whiteningLevel, ruddyLevel);
        mTXCameraRecord.setBeautyDepth(beautyLevel, whiteningLevel);
    }

    @Override
    public void onBeautyDismiss() {
        if (mBottom != null) {
            mBottom.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        if (mTXCameraRecord != null) {
            mTXCameraRecord.stopRecord();
            mTXCameraRecord.setVideoRecordListener(null);
            mTXCameraRecord.stopCameraPreview();
            mTXCameraRecord.stopBGM();
            mTXCameraRecord = null;
            abandonAudioFocus();
        }
        if (mVideoView != null) {
            mVideoView.clearLog();
            mVideoView = null;
        }
        if (mHomeKeyEventReceiver != null) {
            unregisterReceiver(mHomeKeyEventReceiver);
        }
    }

    // 等待写入完成
    Runnable muercheck = new Runnable() {
        @Override
        public void run() {
            try {
                while (muxering) {
                    Thread.sleep(200);
                }
                mHandler.obtainMessage(0).sendToTarget();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: // 返回到首页
                    LoadingDialogFragment.setWasSpinning();
                    break;
            }
        }
    };

    public void setState(State state) {
        this.state = state;
    }

    public class GestureDetetor extends GestureDetector.SimpleOnGestureListener {
        private static final int FLING_MIN_DISTANCE = 100;
        private static final int FLING_MIN_VELOCITY = 0;

        @Override
        public boolean onDown(MotionEvent motionEvent) {
            setState(State.DRAG);
            return false;
        }

        //猛滑动
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (!mRecording) {
                if (state == State.DRAG) {
                    if (mRecyclerView.getAdapter() instanceof FilterAdapter) {
                        FilterAdapter mAdapter = (FilterAdapter) mRecyclerView.getAdapter();
                        int pos = mAdapter.getSelectedPostion();
                        if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
                                && Math.abs(velocityX) > FLING_MIN_VELOCITY
                                && pos < mAdapter.getItemCount() - 1) { //左滑
                            pos = pos + 1;
                        } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
                                && Math.abs(velocityX) > FLING_MIN_VELOCITY
                                && pos > 0) { //右滑
                            pos = pos - 1;
                        }
                        FilterHelper.Filter filter = FilterHelper.getInstance().getBitmap(pos);
                        Bitmap bmp = null;
                        if (filter.rid != -1) {
                            bmp = BitmapFactory.decodeResource(getResources(), filter.rid);
                        }
                        if (mTXCameraRecord != null) {
                            mTXCameraRecord.setFilter(bmp);
                            mAdapter.setSelectedPostion(pos);
                            mRecyclerView.checkAutoAdjust(pos);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
            return true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (mIvflashMode == 2) {
            ThreadManager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mTXCameraRecord != null) {
                        mTXCameraRecord.toggleTorch(true);
                    }
                }
            }, 200);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        if (mIvflashMode == 2) {
            if (mTXCameraRecord != null) {
                mTXCameraRecord.toggleTorch(false);
            }
        }
    }
}
